// WindowsSocketExample.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "WindowsSocketExample.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;

using namespace std;

UINT ServerThread(LPVOID pParam) {

	cout << "Starting up TCP server \r\n";

	SOCKET server;

	WSADATA wsaData;

	sockaddr_in local;

	int wsaret=WSAStartup(0x101,&wsaData);

	if(wsaret != 0) 
	{
		return 0;
	}

	local.sin_family=AF_INET;
	local.sin_addr.s_addr=INADDR_ANY;
	local.sin_port=htons((u_short)20248);

	server=socket(AF_INET,SOCK_STREAM,0);

	if(server==INVALID_SOCKET)
	{
		return 0;
	}

	if(bind(server, (sockaddr*)&local, sizeof(local)) != 0)
	{
		return 0;
	}

	if(listen(server,10) != 0)
	{
		return 0;
	}

	SOCKET client;
	sockaddr_in from;
	int fromlen = sizeof(from);

	while(true)
	{
		char temp[512];

		client = accept(server, (struct sockaddr*)&from, &fromlen);

		sprintf(temp, "Your IP address is %s\r\n", inet_ntoa(from.sin_addr));

		send(client, temp, strlen(temp), 0);
		cout << "Connection from " << inet_ntoa(from.sin_addr) << "\r\n";

		closesocket(client);
	}

	closesocket(server);

	WSACleanup();

	return 0;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: MFC initialization failed\n"));
		nRetCode = 1;
	}
	else
	{
		// TODO: code your application's behavior here.
		cout << "Press ESCAPE to terminate program\r\n";
		AfxBeginThread(ServerThread,0);
		while(_getch()!=27);
	}

	return nRetCode;
}


